package com.hd.hdxgddcommon.utils.oss;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import com.hd.hdxgddcommon.utils.UploadToRemoteUtil;
import com.hd.hdxgddcommon.utils.oss.storage.AliImg;
import com.hd.hdxgddcommon.utils.oss.storage.AliStorage;
import com.hd.hdxgddcommon.utils.oss.util.CommonUtil;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class OSSUtil {

    /**
     * @return OSSClient oss客户端
     * @throws
     * @Title: getOSSClient
     * @Description: 获取oss客户端
     */
    public static OSSClient getOSSClient() {
        @SuppressWarnings("deprecation")
        OSSClient ossClient = new OSSClient(OSSConfig.ENDPOINT, OSSConfig.ACCESSKEYID, OSSConfig.ACCESSKEYSECRET);
        return ossClient;
    }

    /**
     * @param ossClient  oss客户端
     * @param url        URL
     * @param bucketName bucket名称
     * @param objectName 上传文件目录和（包括文件名）例如“test/index.html”
     * @return void        返回类型
     * @throws
     * @Title: uploadByNetworkStream
     * @Description: 通过网络流上传文件
     */
    public static void uploadByNetworkStream(OSSClient ossClient, URL url, String bucketName, String objectName) {
        try {
            InputStream inputStream = url.openStream();
            ossClient.putObject(bucketName, objectName, inputStream);
            ossClient.shutdown();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    /**
     * @param ossClient   oss客户端
     * @param inputStream 输入流
     * @param bucketName  bucket名称
     * @param objectName  上传文件目录和（包括文件名） 例如“test/a.jpg”
     * @return void        返回类型
     * @throws
     * @Title: uploadByInputStream
     * @Description: 通过输入流上传文件
     */
    public static void uploadByInputStream(OSSClient ossClient, InputStream inputStream, String bucketName,
                                           String objectName) {
        ossClient.putObject(bucketName, objectName, inputStream);
    }

    /**
     * @param ossClient  oss客户端
     *                   * @param file       上传的文件
     * @param bucketName bucket名称
     * @param objectName 上传文件目录和（包括文件名） 例如“test/a.jpg”
     * @return void        返回类型
     * @throws
     * @Title: uploadByFile
     * @Description: 通过file上传文件
     */
    public static void uploadByFile(OSSClient ossClient, File file, String bucketName, String objectName) {
        try {
            ossClient.putObject(bucketName, objectName, file);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }


    /**
     * @param ossClient  oss客户端
     * @param bucketName bucket名称
     * @param key        文件路径/名称，例如“test/a.txt”
     * @return void            返回类型
     * @throws
     * @Title: deleteFile
     * @Description: 根据key删除oss服务器上的文件
     */
    public static void deleteFile(OSSClient ossClient, String bucketName, String key) {
        ossClient.deleteObject(bucketName, key);
    }

    /**
     * @param ossClient  oss客户端
     * @param bucketName bucket名称
     * @param key        文件路径和名称
     * @return InputStream    文件输入流
     * @throws
     * @Title: getInputStreamByOSS
     * @Description:根据key获取服务器上的文件的输入流
     */
    public static InputStream getInputStreamByOSS(OSSClient ossClient, String bucketName, String key) {
        InputStream content = null;
        try {
            OSSObject ossObj = ossClient.getObject(bucketName, key);
            content = ossObj.getObjectContent();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return content;
    }

    /**
     * @param ossClient  oss客户端
     * @param bucketName bucket名称
     * @return List<String>  文件路径和大小集合
     * @throws
     * @Title: queryAllObject
     * @Description: 查询某个bucket里面的所有文件
     */
    public static List<String> queryAllObject(OSSClient ossClient, String bucketName) {
        List<String> results = new ArrayList<String>();
        try {
            // ossClient.listObjects返回ObjectListing实例，包含此次listObject请求的返回结果。
            ObjectListing objectListing = ossClient.listObjects(bucketName);
            // objectListing.getObjectSummaries获取所有文件的描述信息。
            for (OSSObjectSummary objectSummary : objectListing.getObjectSummaries()) {
                results.add(" - " + objectSummary.getKey() + "  " + "(size = " + objectSummary.getSize() + ")");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return results;
    }

    public static String upload(MultipartFile file, AliImg img, String prefix) {
        byte[] buff = CommonUtil.getFileBytes(file);
        AliImg aliImg = AliStorage.uploadImage(buff, img, prefix);
        return aliImg.getUrl();
    }

    public static String upload(MultipartFile file, String prefix) {
        byte[] buff = CommonUtil.getFileBytes(file);
        String url = AliStorage.uploadImage(buff, prefix, getFileType(file));
        return url;
    }

    public static String upload(File file, String prefix) {
        byte[] buff = CommonUtil.getFileBytes(file);
        String url = AliStorage.uploadImage(buff, prefix, getFileType(file));
        return url;
    }

    public static String uploadByBase64(String base64File, String prefix) {
        byte[] bytes = UploadToRemoteUtil.base64ToBytes(base64File);
        String url = AliStorage.uploadImage(bytes, prefix);
        return url;
    }

    public static String getFileType(MultipartFile file) {
        //获取文件全名
        String originalFilename = file.getOriginalFilename();
        //对文文件的全名进行截取然后在后缀名进行删选。
        int begin = originalFilename.indexOf(".");
        int last = originalFilename.length();
        //获得文件后缀名
        String suffix = originalFilename.substring(begin, last);
        //我这边需要的xlsx文件所以说我这边直接判断就是了
        return suffix;
    }

    public static String getFileType(File file) {
        //获取文件全名
        String fileName = file.getName();
        //对文文件的全名进行截取然后在后缀名进行删选。
        int begin = fileName.indexOf(".");
        int last = fileName.length();
        //获得文件后缀名
        String suffix = fileName.substring(begin, last);
        //我这边需要的xlsx文件所以说我这边直接判断就是了
        return suffix;
    }

    public static  String approvalFile( MultipartFile filecontent){
        OutputStream os = null;
        InputStream inputStream = null;
        String fileName = null;
        try {
            inputStream = filecontent.getInputStream();
            fileName = filecontent.getOriginalFilename();
//            log.info("fileName="+fileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            String path;
            String OS = System.getProperty("os.name");
            if(OS.toLowerCase().startsWith("win")){
                path = "F:\\test\\";
            }else {
                path = "/root/hdxgdd/image";
            }

            // 2、保存到临时文件
            // 1K的数据缓冲
            byte[] bs = new byte[1024];
            // 读取到的数据长度
            int len;
            // 输出的文件流保存到本地文件
            File tempFile = new File(path);
            if (!tempFile.exists()) {
                tempFile.mkdirs();
            }
            os = new FileOutputStream(tempFile.getPath() + File.separator + fileName);
            // 开始读取
            while ((len = inputStream.read(bs)) != -1) {
                os.write(bs, 0, len);
            }
            return tempFile.getPath() + File.separator + fileName;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 完毕，关闭所有链接
            try {
                os.close();
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "";
    }
}
